// mapwidget.cpp
#include "mapwidget.h"
#include <QPainter>
#include <QPen>
#include <QBrush>
#include <QDebug>
#include <QMouseEvent>
#include <QPixmap> // ***新增：包含 QPixmap 头文件***
#include <QPixmap>
#include <limits>
#include<QLineF>
#include<cmath>
Mapwidget::Mapwidget(QWidget *parent) : QWidget(parent)
{
    // ***移除样式表设置，因为我们要手动绘制背景***
    // this->setStyleSheet("QWidget { border-image: url(:/map.png) 0 0 0 0 stretch stretch; }");

    this->resize(800, 600); // 确保有尺寸
//    carfree[555]=QPoint(123,123);
//    carbuzy[222]=QPoint(555,333);
//    carweight[555]=64;
//    carweight[222]=55;
//    road.push_back(QPoint(166,88));
//    road.push_back(QPoint(323,88));

    this->setAutoFillBackground(true);
    this->setAttribute(Qt::WA_NoSystemBackground, false);
    this->setAttribute(Qt::WA_TranslucentBackground, false);
    this->setAttribute(Qt::WA_OpaquePaintEvent, false);
    this->setAttribute(Qt::WA_PaintOnScreen, true);
    gridPoints.append(QPoint(32,29));
       gridPoints.append(QPoint(212,29));
       gridPoints.append(QPoint(585,31));
       gridPoints.append(QPoint(735,30));
       gridPoints.append(QPoint(885,31));
       gridPoints.append(QPoint(1033,33));
       gridPoints.append(QPoint(1183,33));
       gridPoints.append(QPoint(33,144));
       gridPoints.append(QPoint(215,146));
       gridPoints.append(QPoint(584,145));
       gridPoints.append(QPoint(737,142));
       gridPoints.append(QPoint(886,145));
       gridPoints.append(QPoint(1033,146));
       gridPoints.append(QPoint(1183,144));
       gridPoints.append(QPoint(33,252));
       gridPoints.append(QPoint(218,253));
       gridPoints.append(QPoint(403,257));
       gridPoints.append(QPoint(583,253));
       gridPoints.append(QPoint(733,252));
       gridPoints.append(QPoint(883,257));
       gridPoints.append(QPoint(1032,252));
       gridPoints.append(QPoint(1186,252));
       gridPoints.append(QPoint(34,364));
       gridPoints.append(QPoint(214,366));
       gridPoints.append(QPoint(401,368));
       gridPoints.append(QPoint(584,371));
       gridPoints.append(QPoint(731,367));
       gridPoints.append(QPoint(882,369));
       gridPoints.append(QPoint(1033,365));
       gridPoints.append(QPoint(1183,364));
       gridPoints.append(QPoint(35,486));
       gridPoints.append(QPoint(217,487));
       gridPoints.append(QPoint(395,484));
       gridPoints.append(QPoint(579,488));
       gridPoints.append(QPoint(732,486));
       gridPoints.append(QPoint(878,488));
       gridPoints.append(QPoint(1033,487));
       gridPoints.append(QPoint(1181,487));
       gridPoints.append(QPoint(29,602));
       gridPoints.append(QPoint(217,600));
       gridPoints.append(QPoint(399,603));
       gridPoints.append(QPoint(580,602));
       gridPoints.append(QPoint(735,599));
       gridPoints.append(QPoint(879,603));
       gridPoints.append(QPoint(1029,605));
       gridPoints.append(QPoint(1182,602));
       gridPoints.append(QPoint(29,719));
       gridPoints.append(QPoint(212,722));
       gridPoints.append(QPoint(394,718));
       gridPoints.append(QPoint(582,721));
       gridPoints.append(QPoint(734,722));
       gridPoints.append(QPoint(880,724));
       gridPoints.append(QPoint(1033,716));
       gridPoints.append(QPoint(1180,719));
       gridPoints.append(QPoint(27,835));
       gridPoints.append(QPoint(212,835));
       gridPoints.append(QPoint(394,840));
       gridPoints.append(QPoint(579,839));
       gridPoints.append(QPoint(734,839));
       gridPoints.append(QPoint(883,843));
       gridPoints.append(QPoint(25,953));
       gridPoints.append(QPoint(212,956));
       gridPoints.append(QPoint(396,956));
       gridPoints.append(QPoint(577,960));
       gridPoints.append(QPoint(735,953));
       gridPoints.append(QPoint(876,952));
       gridPoints.append(QPoint(1176,956));
       qDebug() << "Number of grid points stored:" << gridPoints.size();
       connect(this,&Mapwidget::updateemit,this,&Mapwidget::hanleupdate);


       connect(this,&Mapwidget::chlocation,this,&Mapwidget::locationChanged);
       connect(this,&Mapwidget::chfinall,this,&Mapwidget::finallLocationChanged);
       connect(this,&Mapwidget::chlocationok,this,&Mapwidget::locationOkChanged);
       connect(this,&Mapwidget::chfinallok,this,&Mapwidget::finallLocationOkChanged);
       connect(this,&Mapwidget::chcarfreerm,this,&Mapwidget::carFreeRemoved);
       connect(this,&Mapwidget::chcarfreein,this,&Mapwidget::carFreeAddedOrUpdated);
       connect(this,&Mapwidget::chcarbuzyrm,this,&Mapwidget::carBuzyRemoved);
       connect(this,&Mapwidget::chcarbuzyin,this,&Mapwidget::carBuzyAddedOrUpdated);
       connect(this,&Mapwidget::chweight,this,&Mapwidget::carWeightChanged);
       connect(this,&Mapwidget::chorderrm,this,&Mapwidget::orderRemoved);
       connect(this,&Mapwidget::chorderin,this,&Mapwidget::orderWeightChanged);
       connect(this,&Mapwidget::chcarweight,this,&Mapwidget::carWeightChanged);
       connect(this,&Mapwidget::chroadin,this,&Mapwidget::roadPathSegmentAdded);
       connect(this,&Mapwidget::chroadclear,this,&Mapwidget::roadPathCleared);
       connect(this,&Mapwidget::chnoworder,this,&Mapwidget::nowOrderChanged);
       connect(this,&Mapwidget::chmarchantin,this,&Mapwidget::changemarchantin);
       connect(this,&Mapwidget::chmarchantrm,this,&Mapwidget::changemarchantrm);
       connect(this,&Mapwidget::chorderendin,this,&Mapwidget::changeorderendin);
       connect(this,&Mapwidget::chorderendrm,this,&Mapwidget::changeorderendrm);
       connect(this,&Mapwidget::chorderstartin,this,&Mapwidget::changeorderstartin);
       connect(this,&Mapwidget::chorderstartrm,this,&Mapwidget::changeorderstartrm);
       connect(this,&Mapwidget::chorderi,this,&Mapwidget::changeorderi);
        connect(this,&Mapwidget::chorderr,this,&Mapwidget::changeorderr);
//       order.insert(123);
//       orderstart[123]=gridPoints[5];
//       orderend[123]=gridPoints[46];
//       order.insert(555);
//       orderstart[555]=gridPoints[15];
//       orderend[555]=gridPoints[30];
}

void Mapwidget::mousePressEvent(QMouseEvent *ev)
{
    QPoint clickedPos = ev->pos(); // 获取鼠标点击的精确位置
    int flagx=0;
    int flagy=0;
    if(locationok&&finallok)
        return;

     // 遍历所有网格点，找到最近的一个
     for (const QPoint &gridP : gridPoints) {
         // 手动计算距离平方，解决 'lengthSquared' 错误
        if(clickedPos.x()>gridP.x()-10&&clickedPos.x()<gridP.x()+10)
            flagx=1;
        if(clickedPos.y()>gridP.y()-10&&clickedPos.y()<gridP.y()+10)
            flagy=1;
        if(flagx||flagy)
            break;
     }
    if(flagx||flagy)
    {
        if(locationok==0)
         location = clickedPos;
        else if(finallok==0)
          finall=clickedPos;
        emit changepos();
    }
    update();
    //qDebug() << location;
}

void Mapwidget::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    // *** 关键：直接用 QPainter 绘制背景图片 ***
    QPixmap backgroundImage(":/map.png"); // 加载你的地图图片
    if (!backgroundImage.isNull()) {
        // 使用 drawPixmap 将图片绘制到整个控件区域
        painter.drawPixmap(rect(), backgroundImage);
       // qDebug() << "Background image drawn by QPainter. Image size:" << backgroundImage.size();
    } else {
       // qDebug() << "ERROR: Failed to load background image ':/map.png' with QPixmap. Filling with red.";
        // 如果图片加载失败，用红色填充，方便调试
        painter.fillRect(rect(), Qt::red);
    }
    if(!road.empty())
    {
        if (road.size() >= 2) // 至少需要两个点才能画出一条线段（或矩形）
           {
               QPen pathPen(QColor("#ff5500")); // 路径线的颜色
               pathPen.setWidth(3); // 路径线的宽度
               painter.setPen(pathPen);
               QBrush pathBrush(QColor("#ff5500")); // 路径矩形的填充颜色
               painter.setBrush(pathBrush); // 设置画刷，用于绘制填充的矩形

               for (int i = 0; i < road.size() - 1; ++i) {
                   QPoint startPoint = road[i];
                   QPoint endPoint = road[i+1];
                    //qDebug()<<startPoint<<"  dddd";
                   // 调试输出，确认当前处理的线段
                   //qDebug() << "Drawing segment from" << startPoint << "to" << endPoint;

                   if (startPoint != QPoint() && endPoint != QPoint() && startPoint != endPoint) {
                       QLineF centerLine(startPoint, endPoint);
                       double length = centerLine.length();

                       if (length > 0) {
                           double perpX = -(centerLine.dy() / length);
                           double perpY = (centerLine.dx() / length);

                           double halfWidth = pathPen.widthF() / 2.0; // 使用画笔宽度的一半作为半宽

                           QPointF v1 = QPointF(startPoint.x() + perpX * halfWidth, startPoint.y() + perpY * halfWidth);
                           QPointF v2 = QPointF(startPoint.x() - perpX * halfWidth, startPoint.y() - perpY * halfWidth);
                           QPointF v3 = QPointF(endPoint.x() - perpX * halfWidth, endPoint.y() - perpY * halfWidth);
                           QPointF v4 = QPointF(endPoint.x() + perpX * halfWidth, endPoint.y() + perpY * halfWidth);

                           QPolygonF rectanglePolygon;
                           rectanglePolygon << v1 << v4 << v3 << v2; // 确保顺序正确，形成闭合多边形

                           // 绘制填充的矩形，而不是只画边框
                           painter.drawPolygon(rectanglePolygon);
                       }
                   }
               }
           }
    }
    if(identity==0)
    {
          QPen pen(QColor(55,55,55));
          pen.setWidth(3);
          painter.setPen(pen);
          QBrush brush(Qt::cyan);
          painter.setBrush(brush);
          painter.drawEllipse(location,10,10);
          for (const QPoint &p : gridPoints) {
                  painter.drawEllipse(p, 5, 5); // 绘制一个小圆点在每个位置
              }
          for (const QPoint &p : orderstart) {
                  painter.drawEllipse(p, 5, 5); // 绘制一个小圆点在每个位置
              }
          pen.setColor(QColor(55,55,55));
          painter.setPen(pen);
          brush.setColor("red");
          painter.setBrush(brush);
          painter.drawEllipse(finall,10,10);
          brush.setColor("#55ff7f");
          painter.setBrush(brush);
          for (auto i:carfree ) {
              QPoint p=i;
                  painter.drawEllipse(p, 5, 5); // 绘制一个小圆点在每个位置
              }
          brush.setColor("orange");
          painter.setBrush(brush);
          for (auto i:carbuzy ) {
              QPoint p=i;
                  painter.drawEllipse(p, 5, 5); // 绘制一个小圆点在每个位置
              }
    }
    else
    {
        QPen pen(QColor(55,55,55));
        pen.setWidth(3);
        painter.setPen(pen);
        QBrush brush(Qt::cyan);
        brush.setColor("#00ffff");
        pen.setBrush(brush);
        for (const QPoint &p : orderstart) {
                painter.drawEllipse(p, 10, 10); // 订单起点
            }
        brush.setColor("yellow");
        painter.setBrush(brush);
        painter.drawEllipse(location,10,10);
        for (const QPoint &p : gridPoints) {
                painter.drawEllipse(p, 5, 5); // 绘制一个小圆点在每个位置
            }
        brush.setColor("#55ff7f");
        painter.setBrush(brush);
        for (auto i:carfree ) {
            QPoint p=i;
            if(p==location)
                continue;
                painter.drawEllipse(p, 5, 5); // 绘制一个小圆点在每个位置
            }
        brush.setColor("orange");
        painter.setBrush(brush);
        for (auto i:carbuzy ) {
            QPoint p=i;
            if(p==location)
                continue;
                painter.drawEllipse(p, 5, 5); // 绘制一个小圆点在每个位置
            }
        if(noworder!=-1)
        {
            brush.setColor("red");
            painter.setBrush(brush);
            painter.drawEllipse(orderend[noworder],10,10);
        }
    }

}

void Mapwidget::hanleupdate()
{
    update();
}

void Mapwidget::locationChanged(const QPoint &newLocation)
{
    location=newLocation;
}

void Mapwidget::locationOkChanged(int value)
{
    locationok=value;
}

void Mapwidget::finallLocationChanged(const QPoint &pos)
{
    finall=pos;
}

void Mapwidget::finallLocationOkChanged(bool ok)
{
    finallok=ok;
}

void Mapwidget::carFreeAddedOrUpdated(long long id, const QPoint &pos)
{
    carfree[id]=pos;
}

void Mapwidget::carFreeRemoved(long long id)
{
    carfree.remove(id);
}

void Mapwidget::carBuzyAddedOrUpdated(long long id, const QPoint &pos)
{
    carbuzy[id]=pos;
}

void Mapwidget::carBuzyRemoved(long long id)
{
    carbuzy.remove(id);
}

void Mapwidget::carWeightChanged(long long id, int weight)
{
    carweight[id]=weight;
}

void Mapwidget::orderWeightChanged(long long orderId, int weight)
{
    this->weight[orderId]=weight;
}

void Mapwidget::orderRemoved(long long orderId)
{
    order.remove(orderId);
}

void Mapwidget::roadPathSegmentAdded(const QPoint &point)
{
    road.push_back(point);
}

void Mapwidget::roadPathCleared()
{
    road.clear();
}

void Mapwidget::changemarchantin(long long id, QPoint p)
{
    marchant[id]=p;
}

void Mapwidget::changemarchantrm(long long id)
{
    marchant.remove(id);
}

void Mapwidget::nowOrderChanged(long long orderId)
{
    noworder=orderId;
}
void Mapwidget::changeorderstartrm(long long i)
{
    orderstart.remove(i);
}

void Mapwidget::changeorderstartin(long long i, QPoint q)
{
    orderstart[i]=q;
}

void Mapwidget::changeorderendrm(long long i)
{
     orderend.remove(i);
}

void Mapwidget::changeorderendin(long long i, QPoint q)
{

        orderend[i] = q; // Add or update the order end point


}

void Mapwidget::changeorderr(long long i)
{
    order.remove(i);
}
void Mapwidget::changeorderi(long long i)
{
    order.insert(i);
}
